//
//  EvaluatViewController.m
//  随便点
//
//  Created by ZC on 15/4/6.
//  Copyright (c) 2015年 qfsoft. All rights reserved.
//

#import "EvaluatViewController.h"
#import "ShopEvaluateCell.h"
#import "AppDelegate.h"
#import "Evaluation.h"



@interface EvaluatViewController (){
    AppDelegate *dele;
    NSMutableDictionary *EvaluationDic;  //评论字典
    NSMutableArray *EvaluationArray;    //评论数组
    NSMutableDictionary *EvaluationListDic;  //评论列表字典
    NSMutableArray *EvaluationListArray;    //评论列表数组
    
    NSString *str1;
    NSString *str2;
    NSString *str3;
    NSString *str4;
    
    float Taverage;
    
    int i;
}

@property (nonatomic,strong)RefreshControl * refreshControl;


@end

@implementation EvaluatViewController

- (void)viewDidLoad {
    self.navigationItem.hidesBackButton = YES;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = item;
    
    dele = (AppDelegate *)[[UIApplication sharedApplication]delegate];

    EvaluationArray=[NSMutableArray array];
    EvaluationListArray=[NSMutableArray array];
    //默认跳过条数为0
    str3 = @"0";
    

    
//    请求评论数据
    [self setUpEvaluationCount];
    
    //获取评价列表
    [self SetUpEvaluate];
    
    //上拉刷新
    
    self.ShopEvaluatTableView.dataSource = nil;
    
    _refreshControl=[[RefreshControl alloc] initWithScrollView:self.ShopEvaluatTableView delegate:self];
    _refreshControl.topEnabled=NO;
    _refreshControl.bottomEnabled=YES;
    
    [self.ShopEvaluatTableView reloadData];


    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshControl:(RefreshControl *)refreshControl didEngageRefreshDirection:(RefreshDirection)direction
{
    if (direction==RefreshDirectionTop)
    {
        
        [EvaluationListArray removeAllObjects];
        
    }
    else if (direction==RefreshDirectionBottom)
    {
        
    }
    
    __weak typeof(self)weakSelf=self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf)strongSelf=weakSelf;
        [strongSelf reloadData];
    });
    
}

-(void)reloadData
{
    
    str3=[NSString stringWithFormat:@"%d",[str3 intValue]+10];
    
    [self SetUpEvaluate];

    if (self.refreshControl.refreshingDirection==RefreshingDirectionTop)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionTop];
    }
    else if (self.refreshControl.refreshingDirection==RefreshingDirectionBottom)
    {
        [self.refreshControl finishRefreshingDirection:RefreshDirectionBottom];
        
    }
    
        [self.ShopEvaluatTableView reloadData];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //返回cell的行数
    return EvaluationListArray.count;
//    return 5;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UINib *nib = [UINib nibWithNibName:@"ShopEvaluateCell" bundle:nil];
    [self.ShopEvaluatTableView registerNib:nib forCellReuseIdentifier:@"shopEvaluate"];
        
        
    static NSString *cellIdentifier=@"shopEvaluate";
    ShopEvaluateCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    
    Evaluation *evalu = EvaluationListArray[indexPath.row];
    
    cell.evaluate.text=[NSString stringWithFormat:@"%@",evalu.evaContent];

    //时间戳转换成时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[evalu.evaTime doubleValue]/1000];
    NSString *timeSp = [formatter stringFromDate:confromTimesp];
    cell.time.text=timeSp;

    cell.userId.text=[NSString stringWithFormat:@"%@",evalu.evaUserId];
    cell.evaluate.text=[NSString stringWithFormat:@"%@",evalu.evaContent];
    
    //店铺总评分
    self.totalScore.text=[NSString stringWithFormat:@"%@",evalu.evaEvarage];
    
    TQStarRatingView *starRatingView1 = [[TQStarRatingView alloc] initWithFrame:CGRectMake(30, 120, [UIScreen mainScreen].bounds.size.width-230, 30) numberOfStar:5];
    starRatingView1.delegate = self;
    //传入参数，则该星星不可修改
    
    [starRatingView1 StarScore:[self.totalScore.text floatValue]/5];
    [self.view addSubview:starRatingView1];
    
    //显示星级评论等级
    TQStarRatingView *starRatingView = [[TQStarRatingView alloc] initWithFrame:CGRectMake(250, 12, [UIScreen mainScreen].bounds.size.width-270, 15) numberOfStar:5];
    starRatingView.delegate = self;
    
    //传入参数，则该星星不可修改
    [starRatingView StarScore:[evalu.evaEvaluate floatValue]/5];
    
    [cell addSubview:starRatingView];

    return cell;
}


#pragma mark - 请求数据：获取各个星级的评价总数
-(void)setUpEvaluationCount{
    
    str1 = @"http://www.51anys.com:8080/waimaiwang/shop/getEvaluateNumber/";
    str2 = [NSString stringWithFormat:@"%@",dele.spid];  //店铺ID
    str4 =[NSString stringWithFormat:@"%@%@",str1,str2];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str4]];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        EvaluationDic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:EvaluationDic waitUntilDone:YES];

            Evaluation *eva=[[Evaluation alloc]init];
            eva.oneLabel=EvaluationDic[@"one"];
            eva.twoLabel=EvaluationDic[@"two"];
            eva.threeLabel=EvaluationDic[@"three"];
            eva.fourLabel=EvaluationDic[@"four"];
            eva.fiveLabel=EvaluationDic[@"five"];
        
            [EvaluationArray addObject:eva];
        
        //加载评分人数
        [self setUpProgressLabel];


    }];
}

#pragma mark - 加载各星级评论人数
-(void)setUpProgressLabel{
    
    Evaluation *evalu=EvaluationArray[i];

    for (i=0; i<EvaluationArray.count; i++) {
    
        self.oneLabel.text=[NSString stringWithFormat:@"%@",evalu.oneLabel];
        self.twoLabel.text=[NSString stringWithFormat:@"%@",evalu.twoLabel];
        self.threeLabel.text=[NSString stringWithFormat:@"%@",evalu.threeLabel];
        self.fourLabel.text=[NSString stringWithFormat:@"%@",evalu.fourLabel];
        self.fiveLabel.text=[NSString stringWithFormat:@"%@",evalu.fiveLabel];

    }
        self.totalLabel.text=dele.evaluateCount;
    

    [self setUpProgressValue];
}


-(void)refreshData{
    
}

#pragma mark - 加载各星级进度条
-(void)setUpProgressValue{
    self.oneProgress.progress=[self.oneLabel.text floatValue]/[self.totalLabel.text floatValue];
    self.twoProgress.progress=[self.twoLabel.text floatValue]/[self.totalLabel.text floatValue];
    self.threeProgress.progress=[self.threeLabel.text floatValue]/[self.totalLabel.text floatValue];
    self.fourProgress.progress=[self.fourLabel.text floatValue]/[self.totalLabel.text floatValue];
    self.fiveProgress.progress=[self.fiveLabel.text floatValue]/[self.totalLabel.text floatValue];
}

#pragma mark - 请求数据：获取评价列表
-(void)SetUpEvaluate{
    
    str1 = @"http://www.51anys.com:8080/waimaiwang/shop/getEvaluate/";
    str2 = [NSString stringWithFormat:@"%@",dele.spid];  //店铺ID
    
    str4 =[NSString stringWithFormat:@"%@%@/%@",str1,str2,str3];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:str4]];
    NSString *postStr=@"";
    [request setHTTPMethod:@"post"];
    NSData *data=[postStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        EvaluationListDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData) withObject:EvaluationListDic waitUntilDone:YES];

        for(NSDictionary *obj in EvaluationListDic[@"list"]){
            Evaluation *evaluat=[[Evaluation alloc] init];
            evaluat.evaContent=obj[@"content"];
            evaluat.evaEvaluate=obj[@"evaluate"];
            evaluat.evaTime=obj[@"time"];
            evaluat.evaUserId=obj[@"userId"];
            evaluat.evaReply=obj[@"reply"];
            evaluat.evaReplyContent=obj[@"replyContent"];
            evaluat.evaEvarage=EvaluationListDic[@"average"];
            
            
            [EvaluationListArray addObject:evaluat];
        }
        
        self.ShopEvaluatTableView.dataSource = self;
        [self.ShopEvaluatTableView reloadData];
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
